package org.zattix.ejb;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import org.zattix.bean.User;
import org.zattix.util.Logger;

/**
 *
 * @author s.rainoldi
 */
@Stateless
public class UserFacade extends AbstractFacade<User> {
    @PersistenceContext(unitName = "zattixPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UserFacade() {
        super(User.class);
    }
    
    public User getUserByNonce(String nonce){
        User user;
        try {
            user = (User)getEntityManager().createQuery("select u from User u where u.nonce = :nonce").setParameter("nonce", nonce).getSingleResult();
            Logger.log("User found");
        } catch (NoResultException e) {
            Logger.log("No user found. Nonce: " + nonce + "", Logger.INFO);
            return null;
        } catch (NonUniqueResultException e) {
            Logger.log("More than one user found", Logger.WARNING);
            return null;
        }
        return user;
    }
    public User getUserByEmail(String email){
        User user;
        try {
            user = (User)getEntityManager().createQuery("select u from User u where u.email = :email").setParameter("email", email).getSingleResult();
            Logger.log("User found");
        } catch (NoResultException e) {
            Logger.log("No user found. Email: " + email + "", Logger.INFO);
            return null;
        } catch (NonUniqueResultException e) {
            Logger.log("More than one user found", Logger.WARNING);
            return null;
        }
        return user;
    }
    
}
